import React, { useRef, useState, useEffect } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Modal, Space, Table, Input, Switch, App ,Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined,EyeOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {positionpage,positionDelete,positionUpdateStatus  } from '@/services/system/postmanagement';
import { useNavigate } from 'umi';
import { log } from '@antv/g2plot/lib/utils';
import { useOutletContext } from '@umijs/max';
import AuthorizedButton from '@/components/AuthorizedButton';
interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}
const UserManage: React.FC = () => {
  const { modal } = App.useApp();
  const [Userrecords, setUserrecords] = useState<any[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  const [departments, setDepartments] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState(''); // 用于存储搜索框输入的文本
  const navigate = useNavigate();
  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async (params = {}) => {
    try {
      const response = await positionpage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
       ...params
      });

      if (response.code === 200) {
        console.log('response:', response);
        let filteredData = response.data.records;
        if (searchText) {
          // 根据输入的搜索文本进行过滤，这里以userName字段为例，可按需调整
          filteredData = filteredData.filter(record => record.userName.includes(searchText));
        }

        setDepartments(filteredData);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const columns: ProColumns[] = [
    {
      title: '岗位名',
      dataIndex: 'positionName',
    },
    {
      title: '编号',
      dataIndex: 'id',
    },
    {
      title: '岗位描述',
      dataIndex: 'description',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={record.status == 0}
          onChange={(checked) => handleStatusChange(record, checked)}
        />
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => (
        <span>
        <Space split={<Divider type="vertical" />}>
          <AuthorizedButton
            buttonData={buttonData}
            action="edit"
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            编辑
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="delete"
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
              // backgroundColor:'red'
            }}
          >
            删除
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="view"
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            详情
          </AuthorizedButton>
        </Space>
      </span>
      )
    },
  ];

  const handleAdd = () => {
    navigate('/system/postmanagement/add');
  };

  const handleEdit = (record: any) => {
    navigate('/system/postmanagement/edit', {
      state: { record }
    });
  };

  const handleDelete = (record) => {
    console.log('record:', record);
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除岗位 "${record.positionName}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await positionDelete({
            id: record.id
          });

          if (response.code === 200) {
            message.success('删除成功');
            fetchData(); // 刷新列表
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  const handleView = (record: any) => {
    navigate('/system/postmanagement/view', {
      state: { record }
    });
  };



  const handleStatusChange = async (record, checked: boolean) => {
    try {
      const response = await positionUpdateStatus({
        ...record,
        status: checked ? 0 : 1
      });

      if (response.code === 200) {
        message.success('状态更新成功');
        fetchData(); // 刷新表格数据
      } else {
        message.error(response.msg || '状态更新失败');
        // 如果失败，刷新数据以恢复原状态
        fetchData();
      }
    } catch (error) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
      // 如果出错，刷新数据以恢复原状态
      // fetchData();
    }
  };

  return (
    <App>
      <PageContainer>
        <Space style={{ marginBottom: 16 }}>
        <AuthorizedButton
          buttonData={buttonData}
          action="add"
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增
        </AuthorizedButton>
          <Input
            placeholder="请输入用户名进行搜索"
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
        </Space>
        <Table
          columns={columns}
          dataSource={departments}
          pagination={{
           ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              fetchData({ current: page, size: pageSize });
            },
          }}
        />
      </PageContainer>
    </App>
  );
};

export default UserManage;
